import { lagoRegurl, lagouUrl } from '.'
import { getBrowser, logger, setPageCookie } from '@/utils'
import type { State } from '@/types'

export async function getAllBooksList(cookie: string) {
  const browser = await getBrowser()
  if (!browser) return
  const page = await browser.newPage()
  let data: State[] // 存储小册数据的变量
  try {
    await setPageCookie(page, cookie)
    await page.goto(lagouUrl)
    logger.info('正在获取小册列表')
    await page.click('.tab-list > .tab-item:nth-child(2)')
    await page.waitForSelector('.course-title-border > .more-course')
    await page.click('.course-title-border > .more-course')
    // await page.waitForSelector('.books-container')
    // 创建一个Promise
    const dataPromise = new Promise<State[]>((resolve) => {
      // 获取所有的书籍
      page.on('response', async (response) => {
        const url = response.url()
        if (url.includes(lagoRegurl)) {
          const allCourse = await response.json()
          const {
            content: { allCoursePurchasedRecord = {} },
          } = allCourse
          const memberAdsBar =
            allCoursePurchasedRecord.filter((item: { title: string }) => {
              return item.title === '专栏课程'
            })?.[0]?.courseRecordList ?? []
          if (memberAdsBar.length) {
            logger.info(`共有${memberAdsBar.length}本专栏`)
            data = memberAdsBar
          } else {
            logger.warn('获取专栏数量为0，可能是 cookie 失效了，或者是没有购买小册')
          }
          resolve(data) // 解析Promise并返回数据
        }
      })
    })

    // 等待Promise解析并返回数据
    data = await dataPromise
  } finally {
    // await browser.close() // 关闭浏览器
    return data
  }
}
